//
//  LightSersorViewController.m
//  Gunz
//
//  Created by Joggy on 16/7/2.
//  Copyright © 2016年 NUPT. All rights reserved.
//

#import "LightSensorViewController.h"
#import "GZConst.h"
#import "QYNotice.h"

@interface LightSensorViewController ()<UITableViewDelegate, UITableViewDataSource> {
    
    UITableView *table;
    NSMutableArray *data;
    
}

@end

@implementation LightSensorViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self prepareForNav];
    [self prepareForLayout];
}

-(void)prepareForNav{
    [super prepareForNav];
    self.title = @"光线传感器";
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeSystem];
    leftButton.frame = CGRectMake(0, 0, 44, 44);
    [leftButton setAttributedTitle:[[NSAttributedString alloc] initWithString:@"完成" attributes:@{NSForegroundColorAttributeName: CUSTOM_GREEN}] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(completeCapture) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeSystem];
    rightButton.frame = CGRectMake(0, 0, 44, 44);
    [rightButton setAttributedTitle:[[NSAttributedString alloc] initWithString:@"获取" attributes:@{NSForegroundColorAttributeName: CUSTOM_GREEN}] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(onceCapture) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
}

-(void)prepareForLayout {
    [super prepareForLayout];
    data = [[NSMutableArray alloc] init];
    table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight - 64) style:UITableViewStylePlain];
    table.delegate = self;
    table.dataSource = self;
    table.backgroundColor = [UIColor clearColor];
    table.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, 10)];
    table.separatorStyle = UITableViewCellSelectionStyleBlue;
    table.separatorColor = [UIColor colorWithRed:0.85 green:0.85 blue:0.85 alpha:1];
    table.showsVerticalScrollIndicator = false;
    table.tableFooterView = [[UIView alloc] init];
    [table registerClass:[UITableViewCell class] forCellReuseIdentifier:@"LSCell"];
    [self.view addSubview:table];
}

- (void)completeCapture {
    if(data.count > 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"是否保存所采集的数据" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //保存数据
            UIAlertController *saveAlert = [UIAlertController alertControllerWithTitle:@"数据名" message:@"" preferredStyle:UIAlertControllerStyleAlert];
            [saveAlert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
                textField.placeholder = @"请输入数据名";
            }];
            [saveAlert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                UITextField *textField = saveAlert.textFields[0];
                NSString *superPath = [NSString stringWithFormat:@"%@/%@", documentBasePath, GZUserLightPath];
                NSFileManager *manager = [NSFileManager defaultManager];
                if(![manager fileExistsAtPath:superPath]) {
                    [manager createDirectoryAtPath:superPath withIntermediateDirectories:true attributes:nil error:nil];
                }
                if([textField.text isEqualToString:@""]) {
                    textField.text = [GZConst getCurrentDateFormate];
                }
                NSString *savePath = [NSString stringWithFormat:@"%@/%@/%@", documentBasePath, GZUserLightPath, textField.text];
                if([data writeToFile:savePath atomically:true]) {
                    [self dismissViewControllerAnimated:true completion:nil];
                }
                else {
                    [QYNotice showError:@"保存失败" toView:self.view];
                    [QYNotice dismissWithDelay:3];
                }
            }]];
            [saveAlert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
            [self presentViewController:saveAlert animated:true completion:nil];
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"不保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //保存数据
            [self dismissViewControllerAnimated:true completion:nil];
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:alert animated:true completion:nil];
    }
    else {
        [self dismissViewControllerAnimated:true completion:nil];
    }
}

- (void)onceCapture {
    CGFloat light = [[UIScreen mainScreen] brightness];
    
    [data addObject:[NSString stringWithFormat:@"%@第%ld次亮度\t%f", [GZConst getCurrentDateFormate], (long)data.count + 1, light]];
    
    [table reloadData];
    [table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:data.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:true];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma 代理方法

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:true];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 47;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return data.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LSCell"];
//    NSString *title = @"第";
//    title = [title stringByAppendingString:[NSString stringWithFormat:@"%ld", (long)indexPath.row + 1]];
//    title = [title stringByAppendingString:@"次\t"];
//    title = [title stringByAppendingString:data[indexPath.row]];
//    cell.textLabel.text = title;
    cell.textLabel.text = data[indexPath.row];
    return cell;
}

@end
